#pragma once

#include<iostream>
#include<string>
#include<fstream>
#include<unordered_map>
#include <utility>


#include "Common.hpp"
#include"Log.hpp"
using namespace LogModule;

const std::string gpath = "./";
const std::string gdictname = "dict.txt";
const std::string gsep = ": ";

class Dictionary
{
private:
    //加载字典
    bool LoadDictionary()
    {
        //以文件形式打开dict.txt
        std::string file = _path + _filename;
        std::ifstream in(file.c_str());
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR) << "opean file" << file << "error" ;
            return false;
        }
        //读取文件中的字符串并切分（love: 爱）
        std::string line;
        while(std::getline(in,line))
        {
            std::string l_key;
            std::string r_value;
            if(SplitString(line , &l_key , &r_value , gsep))
            {
                //切分成功加载进字典
                _dictionary.insert(std::make_pair(l_key, r_value));
            }
        }

        in.close();
        return true;
    }
public:
    //若参数不是全缺省的，要把缺省参数放在不缺省的后面
    Dictionary(const std::string &path = gpath,const std::string &filename = gdictname)
    :_path(path)
    ,_filename(filename)
    {
        LoadDictionary();
        Print();
    }

    //翻译
    std::string Translate(const std::string &world)
    {
        auto iter = _dictionary.find(world);
        if(iter == _dictionary.end()) return "查无此词！";
        return iter->second;
    }

    void Print()
    {
        for(auto &item:_dictionary)
        {
            std::cout << item.first << ":" << item.second << std::endl;
        }
    }
    ~Dictionary()
    {}
private:
    std::unordered_map<std::string, std::string > _dictionary;
    std::string _path;
    std::string _filename;
};